var friendBox;

function addToFriend(id) {
  return addToFriends(id);
}

function addToFriends(id, obj) {
  if (friendBox == undefined) {
    friendBox = new MessageBox({title: add_box_title, width: 400});
    if (!window.Dropdown) {
      attachScript('uiControls', 'js/lib/ui_controls.js');
      addCss('css/ui_controls.css');
    }
  }
  var url, act;
  url = 'friends_ajax.php';
  act = 'request_form';

  friendBox.removeButtons();
  friendBox.addButton({label: friends_cancel, style: 'button_no', onClick: function(){friendBox.hide();}});
  friendBox.addButton({label: Add_to_friends, onClick: function(){
    var form = ge('addFriendForm');
    if (!form) return;
    var params = serializeForm(form);
    Ajax.postWithCaptcha(url, params, {onSuccess: function(ajax, responseText){
      try {
        var response = eval('(' + responseText + ')');
        responseText = response.result || response.error || response.text;
      } catch (e) {}
      friendBox.content(responseText).removeButtons();
      friendBox.addButton({label: box_close, onClick: function(){friendBox.hide();}});
      friendBox.show();
      hide(obj);
      setTimeout("friendBox.hide(600)", 1200);
    }});
  }});
  friendBox.content('<div class="box_loader"></div>').show();
  Ajax.postWithCaptcha(url, {act: act, fid: id}, {json: 1, onSuccess: function(ajaxObj, response) {
    if (response.error) {
      friendBox.removeButtons().addButton({label: box_close, style: 'button_no', onClick: function(){friendBox.hide();}});
    }
    friendBox.content(response.text).show();
    if (response.script) {
      var script = response.script.replace(/^[\s\\n]+/g, '');
      eval(script);
    }
  }});
  return false;
}

var friendDeleteBox;
function removeFriend(fid, obj, hash) {
  if (friendDeleteBox == undefined) {
    friendDeleteBox = new MessageBox({title: friends_remove_from_list_title});
  }
  friendDeleteBox.removeButtons();
  friendDeleteBox.addButton({
    onClick: function(){friendDeleteBox.hide(200)},
    style:'button_no',
    label: friends_cancel
  }).addButton({
    onClick: function(){
     Ajax.Post({
       url: 'friends_ajax.php',
       query: {fid: fid, act: 'decline_friend', hash: hash},
       onDone: function(ajaxObj, responseText) {
        hide(obj);
       }
     });
     friendDeleteBox.hide(200);
    },
    label: friend_friend_remove
  });
  friendDeleteBox.loadContent("friends_ajax.php",{'act':'remove_box','fid':fid}).show();
  return false;
}

function showRateBox() {
  addCss('css/privacy.css');
  addCss('css/wiki.css');
  if (rateBox == undefined) {
    rateBox = new MessageBox(
     {title: getLang('global_rating_box_header'), bodyStyle: 'padding:0px', width: '480px', progress: 'rateProgress'}
    );
  }
  rateBox.removeButtons();
  rateBox.addButton({
    onClick: function() { rateBox.hide(200); },
    label: box_close
  });
  rateBox.loadContent("rate.php", {'act':'a_get_rate'}, true).show();
  return false;
}

var voteBox;
function showVoteBox() {
  addCss('css/privacy.css');
  if (voteBox == undefined) {
    voteBox = new MessageBox(
     {title: getLang('rate_voting'), bodyStyle: 'padding:0px', width: '480px', progress: 'voteProgress'}
    );
  }
  voteBox.removeButtons();
  voteBox.addButton({
    style: 'button_no',
    onClick: function() { voteBox.hide(200); },
    label: global_cancel
  });
  voteBox.loadContent("rate.php", {'act':'a_get_vote_box', 'id': ge('mid').value}, true).show();
  return false;
}

var giftBox, giftBoxTitle;
function showGiftBox(title) {
  giftBoxTitle = title;
  if (!giftBox) {
    addCss('css/gifts.css');
    addCss('css/privacy.css');
    if (!window.Dropdown) {
      attachScript('uiControls', 'js/lib/ui_controls.js');
      addCss('css/ui_controls.css');
    }
    giftBox = new MessageBox({title: title, bodyStyle: 'padding:0px', width: '654px', progress:'gifts_progress'});
  }
  giftBox.removeButtons();
  giftBox.addButton({
    onClick: function() { giftBox.hide(200); },
    label: box_close
  });
  giftBox.loadContent("gifts.php", {'act':'a_get_gift_box', 'id': ge('mid').value}, true).show();
  return false;
}

var giftSendBox, selectedGift, giftPrice;
function showGift(num, obj, price, bonus) {
  giftSendBox.show();
  selectedGift = num;
  giftPrice = price;
  if (window.userBalance < price)
    show('gift_error');
  else
    hide('gift_error');
  ge('gift_loader').innerHTML = '<img src="'+base_domain + 'images/gifts/256/' + num +'.jpg" />';
  return false;
}

function doSendGift(num) {
  if (isVisible('send_progress')) return;
  hide('gift_msg_link');
  show('send_progress');
  var onComplete = function(ajaxObj, responseText) {
    hide('send_progress');
    show('gift_msg_link');
    if (ajaxObj.status == 400) {
      show('gift_error');
      ge('gift_error').innerHTML = responseText;
      animate(ge('gift_error').firstChild, {backgroundColor: '#F9F6E7', borderColor: '#D4BC4C'}, 5000);
    } else {
      var result = eval('(' + responseText + ')');
      window.userBalance = result.balance;
      if (result.balance) {
        show('left_balance_box');
        ge('left_balance_box').innerHTML = result.balance_html;
      } else {
        hide('left_balance_box');
      }
      var profileBlock = ge('profile_gifts');
      if (profileBlock) profileBlock.innerHTML = result.profile_html;
      showGiftResult(result.result);
    }
  };
  Ajax.Send("gifts.php", {act:'do_send', to_users: ge('mid').value, giftType: ge('giftType').value, giftNumber: selectedGift, giftText: ge('gift_text').value, hash: giftHash}, {onSuccess: onComplete, onFail: onComplete});
  return false;
}

var giftResultBox;
function showGiftResult(text) {
  if (!giftResultBox) {
    giftResultBox = new MessageBox({title: giftBoxTitle, width: '444px'});
    giftResultBox.addButton({label: box_close, onClick: giftResultBox.hide});
  }
  giftResultBox.content(text).show();
  setTimeout(function(){giftResultBox.hide(400);}, 1200);
}

var curGiftFilter = 0;
function giftsFilter(filter) {
  ge('giftTab'+curGiftFilter).className = 't_filter_off';
  ge('giftTab'+filter).className = 't_filter_selected';
  curGiftFilter = filter;
  show('gifts_progress');
  Ajax.Send('gifts.php', {act: 'a_get_gifts', filter: filter}, function(ajaxObj, responseText) {
    ge('selectGift').innerHTML = responseText;
    hide('gifts_progress');
  });
}

var beFanBox;
function beFan(mid) {
  beFanBox = new MessageBox(
   {title: profile_become_a_fan}
  );
  beFanBox.removeButtons();
  beFanBox.addButton({
    onClick: function(){beFanBox.hide(200)},
    label:box_close
  });
  beFanBox.loadContent("rate.php", {'act':'a_be_fan', 'mid': mid}, true).show();
  return false;
}

function notFan(mid) {
  beFanBox = new MessageBox({title: profile_not_a_fan});
  beFanBox.loadContent("rate.php", {'act':'a_not_fan', 'mid': mid}, true).show();
  return false;
}

// EX ACTIVITY.JS

activity_editor = {

  active:             false,  // Is Editor Visible
  menu_active:        false,  // Is Suggestion Menu Visible
  activity_text:        '',

  activity_blur:        false,
  activity_reblur:      false,

  //
  // Functions to transition between modes
  //

  setup: function(initial_activity) {
    this.activity_text = initial_activity;
  },

  reset: function() {
    ge('edit_activity_text').value='';
    return false;
  },

  show: function() {
    if (!this.active) {
	  historyAjaxHide();
      hide('profile_activity');
      hide('profile_empty_activity');
      this.hide_menu();
      show('activity_editor');
      if (ge('activity_text').firstChild) {
        this.activity_text = ge('activity_text').firstChild.nodeValue;
      }
      ge('edit_activity_text').value = this.activity_text;
      ge('edit_activity_text').focus();
      ge('edit_activity_text').select();
      this.activity_blur = true;
	  setTimeout(function() { activity_editor.active = true; }, 200);
      // this.active = true;
    } else {
      ge('edit_activity_text').focus();
    }
    return false;
  },

  hide: function() {
    if (!this.active) {
      return;
    }
	setTimeout(function() { activity_editor.active = false; }, 200);
    // this.active = false;
    this.activity_blur = false;
    hide('activity_editor');
    show((this.activity_text != '') ? 'profile_activity' : 'profile_empty_activity');
	//if (this.activity_text != '') {
	//	show('profile_activity');
	//}
    return false;
  },

  toggle_menu: function(event) {
   if (browser.safari || browser.msie || browser.opera) {
     this.activity_reblur = true;
    }
    if (this.menu_active) {
      return this.hide_menu();
    } else {
      return this.show_menu();
    }
  },

  show_menu: function(event) {
    this.menu_active = true;
    ge('edit_activity_toggle').style.backgroundColor='#E1E8ED';
    ge('edit_activity_toggle').style.borderLeftColor='#D2DBE0';
    ge('edit_activity_select').style.display='block';
    return false;
  },

  hide_menu: function() {
    this.menu_active = false;
    ge('edit_activity_toggle').style.backgroundColor='#FFF';
    ge('edit_activity_toggle').style.borderLeftColor='#FFF';
    hide('edit_activity_select');
    return false;
  },

  activity_select: function(elem) {
    if (browser.safari || browser.msie || browser.opera) {
      this.activity_reblur = true;
    }
    this.hide_menu();
    ge('edit_activity_text').value = elem.innerHTML;
    ge('edit_activity_text').focus();
    ge('edit_activity_text').select();
	return false;
  },

  menu_over: function(elem) {
  },

  menu_out: function(elem) {
  },

  blur: function(real_blur) {
  	if (browser.opera && !real_blur) {
		setTimeout(function() { activity_editor.blur(1); }, 100);
		return false;
	}
    if (this.activity_reblur) {
      ge('edit_activity_text').focus();
      this.activity_reblur = false;
      return false;
    }
    if (this.activity_blur) {
      if (ge('edit_activity_text').value != this.activity_text) {
        this.submit_activity_set(ge('edit_activity_text').value);
      } else {
        this.hide();
      }
    }
    return true;
  },

  //
  // Ajax
  //

  activity_set: function(activity) {
    this.activity_text = activity || '';
    this.reset();
    this.hide();
    if (activity != null && activity != '') {
      ge('activity_text').innerHTML = this.activity_text;
      ge('activity_time_link').innerHTML = activity_update_just_now;
    } else {
      ge('activity_text').innerHTML = activity_cant_update;
    }
  },

  submit_activity_set: function(activity) {
    if (activity == null || activity == '') return;
    var selectInput = function() { ge('edit_activity_text').focus(); };
    var unsetBg = function() { hide('activity_progress'); show('activity_links'); };
    var onDone = function(ajax, response) {unsetBg(); activity_editor.activity_set(response); };
    var onFail = function(ajax) { unsetBg(); activity_editor.activity_set(null); };

    var options = {onSuccess: onDone, onFail: onFail, onCaptchaShow: unsetBg, onCaptchaHide: selectInput};
//    ge('edit_activity_text').style.backgroundImage='url('+base_domain+'images/progress_candy_hor.gif)';
    hide('activity_links');
    show('activity_progress');
    Ajax.postWithCaptcha('/profile.php', {'setactivity':activity, 'activityhash': ge('activityhash').value}, options);
    return false;
  },

  activity_cleared: function() {
    this.activity_text = '';
    ge('activity_text').innerHTML = '';
    this.hide();
    ge('activity_blank_nag').innerHTML=activity_deleted;
    setTimeout(function(){
		// hide('activity_blank_nag');
      	ge('activity_blank_nag').innerHTML = activity_change_status;
    }.bind(this), 2500);
  },

  submit_activity_clear: function() {
    this.activity_blur = false;
    ajax = new Ajax();
    ajax.onDone = function(ajaxObj, response) { show('activity_links'); hide('activity_progress'); this.activity_cleared(); }.bind(this);
    ajax.onFail = function(ajaxObj) { show('activity_links'); hide('activity_progress'); this.activity_cleared(); }.bind(this); // fingers crossed
    hide('activity_links');
    show('activity_progress');
    ajax.post('/profile.php', {'clearactivity':'1', 'activityhash': ge('activityhash').value});
    return false;
  },

  //
  // User Interaction
  //

  handle_key_press: function(event) {
    event = event || window.event;
    key_code = event.keyCode || event.which;

    if (key_code == this.KEYS.RETURN) {
      if (ge('edit_activity_text').value != '')
      this.submit_activity_set(ge('edit_activity_text').value);
      return false;
    }
    if (key_code == this.KEYS.ESC) {
      this.hide();
      return false;
    }
    return true;
  },

  KEYS: {BACKSPACE:8,TAB:9,RETURN:13,ESC:27,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46}
}

var historyShown = false;

function getActivityHistory(user_id) {
  ajax = new Ajax();
  ajax.onDone = onGotHistory;
  ajax.onFail = historyAjaxHide;
  historyAjaxProgress();
  ajax.post('/profile.php', {'activityhistory':'1', 'id': user_id});
}

function onGotHistory(ajaxObj, response) {
  historyAjaxShow();
  ge('historyContainer').innerHTML = response;
}

function deleteHistoryItem(item_id) {
  ajax = new Ajax();
  ajax.onDone = onGotHistory;
  ajax.onFail = historyAjaxHide;
  historyAjaxProgress(1);
  ajax.post('/profile.php', {'deletehistoryitem':'1', 'iid': item_id, 'activityhash': ge('activityhash').value});
}

function historyAjaxProgress(onlyshowprogress) {
  if (!onlyshowprogress) {
    hide('historyContainer');
    hide('historyHeader');
  }
  show('historyProgress');
  show('history');
}

function historyAjaxShow() {
  historyShown = true;
  show('history');
  hide('historyProgress');
  show('historyHeader');
  show('historyContainer');
}

function historyAjaxHide() {
  historyShown = false;
  hide('history');
  hide('historyProgress');
  hide('historyHeader');
  hide('historyContainer');
}

// Profile tabs
var tab_masks = {
  'friendsCommon': 1,
  'friends'      : 2,
  'friendsOnline': 4,
  'albums'       : 8,
  'videos'       : 16,
  'questions'    : 32,
  'matches'      : 64,
  'notes'        : 128,
  'groups'       : 256,
  'apps'         : 512,
  'personal'     : 1024,
  'education'    : 2048,
  'career'       : 4096,
  'places'       : 8192,
  'military'     : 16384,
  'opinions'     : 32768,
  'audios'       : 65536,
  'wall'         : 131072,
  'gifts'        : 262144,
  'optional'     : 524288
}

function collapseBox(id, container, dopen, dclose) {
  var box = ge(id);
  if (!box) return;

  var masks = tab_masks;
  var cookie_key = 'closed_tabs';

  var c = geByClass("c", box)[0];
  if (!c) return;
  var newClass = container.parentNode.className == "bOpen" ? "bShut" : "bOpen";
  if (slideToggle(c, 300, function() {
    if (!masks[id]) return;
    var closed_tabs = parseInt(getCookie('remix' + cookie_key));
    if (isVisible(c)) {
      closed_tabs = isNaN(closed_tabs) ? 0 : closed_tabs & ~masks[id];
    } else {
      closed_tabs = isNaN(closed_tabs) ? masks[id] : closed_tabs | masks[id];
    }
    setCookie('remix' + cookie_key, closed_tabs, 360);
  })) {
    container.parentNode.className = newClass;
  }

  return false;
}


function quickReply(id, dopen, dclose, foca){
  var box = ge(id);
  if (!box) return;
  var c = geByClass("r", box)[0];
  if (!c) return;
  if (!isVisible(c))
    slideDown(c, 200, function(){ ge("reply_field").focus(); });
  else
    slideUp(c, 200);
}

// EX FAVE.JS

function addFave() {
  ajax = new Ajax();
  ge('faveProgress').innerHTML = "<IMG SRC='images/upload.gif'>";
  ajax.onDone = function(ajaxObj, response) {
    ge('addToFaves').innerHTML = response;
  }
  ajax.onFail = function(ajaxObj) {
  }
  ajax.post('/fave.php', {'act':'addPerson', 'mid': ge('mid').value, hash: ge('faveHash').value});
}

function deleteFave() {
  ajax = new Ajax();
  ge('faveProgress').innerHTML = "<IMG SRC='images/upload.gif'>";
  ajax.onDone = function(ajaxObj, response) {
    ge('addToFaves').innerHTML = response;
  }
  ajax.onFail = function(ajaxObj) {
  }
  ajax.post('/fave.php', {'act':'deletePerson', 'mid': ge('mid').value, hash: ge('faveHash').value});
}
